# 读取文本 docx 文件
from docx import Document

def read_docx_file(file_path):
    """读取 .docx 文件并返回文本内容"""
    try:
        doc = Document(file_path)
        text = ""
        for paragraph in doc.paragraphs:
            text += paragraph.text + "\n"
        return text
    except Exception as e:
        print(f"读取文件时出错: {e}")
        return None

def read_text_file(file_path):
    """读取纯文本文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except UnicodeDecodeError:
        # 如果UTF-8失败，尝试其他编码
        try:
            with open(file_path, 'r', encoding='gbk') as file:
                return file.read()
        except Exception as e:
            print(f"读取文本文件时出错: {e}")
            return None


def read_srt(path: str):
    """读取 SRT 文件，按区块返回 [ [index, time, *text_lines], ... ]"""
    with open(path, "r", encoding="utf-8") as f:
        lines = f.read().splitlines()
    blocks = []
    current = []
    for line in lines:
        if line.strip() == "":
            if current:
                blocks.append(current)
                current = []
        else:
            current.append(line)
    if current:
        blocks.append(current)
    return blocks


def write_srt(blocks, path: str):
    """写回 SRT 文件，blocks 形如 [ [index, time, *text_lines], ... ]"""
    with open(path, "w", encoding="utf-8") as f:
        for i, block in enumerate(blocks):
            for line in block:
                f.write(str(line).rstrip("\n") + "\n")
            if i != len(blocks) - 1:
                f.write("\n")


def srt2dic(path: str):
    """将 SRT 文件转换为结构化数据列表。

    返回形如：
    [
        {
            "index": int,
            "start": "HH:MM:SS,mmm",
            "end": "HH:MM:SS,mmm",
            "audio_duration": float,
            "text": str,
        },
        ...
    ]
    """
    blocks = read_srt(path)
    items = []
    
    def _parse_ts(ts: str):
        """将 'HH:MM:SS,mmm' 转为秒(float)。解析失败返回 None。"""
        try:
            if not ts:
                return None
            hms, ms = ts.split(",")
            hours, minutes, seconds = hms.split(":")
            total = (
                int(hours) * 3600
                + int(minutes) * 60
                + int(seconds)
                + int(ms) / 1000.0
            )
            return float(total)
        except Exception:
            return None
    for block in blocks:
        if not block:
            continue
        # 解析 index
        index_value = block[0].strip()
        try:
            index_num = int(index_value)
        except Exception:
            # 非标准 index 时，保留原字符串
            index_num = index_value

        # 解析时间行
        start_ts = ""
        end_ts = ""
        if len(block) >= 2:
            time_line = block[1]
            if "-->" in time_line:
                parts = time_line.split("-->")
                if len(parts) == 2:
                    start_ts = parts[0].strip()
                    end_ts = parts[1].strip()

        text_lines = block[2:] if len(block) > 2 else []
        text_joined = "\n".join([line.rstrip("\n") for line in text_lines]).strip()

        start_sec = _parse_ts(start_ts)
        end_sec = _parse_ts(end_ts)
        duration = 0.0
        if start_sec is not None and end_sec is not None:
            duration = round(max(0.0, end_sec - start_sec), 2)

        items.append({
            "index": index_num,
            "start": start_ts,
            "end": end_ts,
            "audio_duration": duration,
            "text": text_joined,
        })

    return items 


def dic2srt(items, path: str):
    """将结构化数据写回为 SRT 文件。

    items 元素可包含：
    - index: int 或 str
    - start: str (HH:MM:SS,mmm)
    - end: str (HH:MM:SS,mmm)
    - text: str (按 \n 切分为多行)
    """
    blocks = []
    for item in items:
        index_value = item.get("index", "")
        start_ts = item.get("start", "")
        end_ts = item.get("end", "")
        text = item.get("text", "")
        lines = text.split("\n") if text else []

        time_line = f"{start_ts} --> {end_ts}".strip()
        block = [index_value, time_line]
        block.extend(lines)
        blocks.append(block)

    write_srt(blocks, path) 



if __name__ == "__main__":
    items = srt2dic("data/test.srt")
    dic2srt(items, "data/test_trans.srt")  